package com.atjava.webspider.html;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.atjava.webspider.util.HttpUtil;

public class DefaultLinkParser implements LinkParser {

	private static final String LINK_REGEXP = "<(?i)a[^>]*href\\s*=\\s*[\"']?([^\"^'^\\s^>]+)[\"']?[^>]*>[^<]*</(?i)a>";
	
	private static final Pattern pattern = Pattern.compile(LINK_REGEXP);
	
	private static LinkParser parser;
	
	private DefaultLinkParser(){
		
	}
	
	public static LinkParser getInstance(){
		if(parser == null)
			parser = new DefaultLinkParser();
		return parser;
	}
	
	public static void main(String[] args) {
		//href = "www.163.com"
		//href = 'www.163.com'
		//href = www.163.com
		//String test1 = "<A \r\n  hrEF   =   \"www.163.com\"  class=\"sdf\"   > Test \r\n sdf </a> ";
		String test2 = "<a href = 'zzz'   onclick=\"alert('test')\">sdfsdfsdf</a>";
		String test3 = "[<A href=\"http://develop.csai.cn/c/200711091203251419.htm\">2</A>]";
		
		LinkParser lp = DefaultLinkParser.getInstance();
		System.out.println(lp.parseLink(test3));
		
	}
	
	public List<String> parseLink(String content){
		List<String> linksList = new ArrayList<String>();
		Matcher um = pattern.matcher(content);
		while(um.find()){
			String link = um.group(1);
			if(HttpUtil.isAvailableLink(link)){
				linksList.add(link);
			}
		}
		return linksList;
	}
	
	public List<String> parseLink(String content,String regex){
		Pattern linkPattern = Pattern.compile(regex);
		List<String> linksList = new ArrayList<String>();
		Matcher um = pattern.matcher(content);
		while(um.find()){
			String link = um.group(1);
			Matcher m = linkPattern.matcher(link);
			if(m.find() && HttpUtil.isAvailableLink(link)){
				linksList.add(link);
			}
		}
		return linksList;
	}
}
